<template>
  <div class="ele-body">
    <div class="tital_war">
      <h1>商品分类</h1>
    </div>
    <a-card :bordered="false">
      <!-- 搜索表单 -->
      <a-form :model="where" :label-col="{ md: { span: 6 }, sm: { span: 24 } }" :wrapper-col="{ md: { span: 18 }, sm: { span: 24 } }">
        <a-row>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="商品分类:">
              <a-select v-model:value="findOptions.pid" placeholder="请选择商品分类" :options="options" @change="getCateLists"> </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="分类状态:">
              <a-select v-model:value="findOptions.is_show" placeholder="请选择分类状态" :options="statusOption" @change="getCateLists"> </a-select>
            </a-form-item>
          </a-col>
          <a-col :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-item label="分类名称:">
              <a-input-search v-model:value="findOptions.cate_name" placeholder="请输入分类名称" @search="getCateLists" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <!-- 表格 -->
      <ele-pro-table ref="table" row-key="id" :datasource="cateLists" :columns="columns" :scroll="{ x: 'max-content' }">
        <template #toolbar>
          <a-space>
            <a-button type="primary" @click="openAddCate()">
              <template #icon>
                <plus-outlined />
              </template>
              <span>添加分类</span>
            </a-button>
          </a-space>
        </template>
        <!-- ID -->
        <template #id="{ record }">
          {{ record.id }}
        </template>
        <!-- 分类明 -->
        <template #cate_name="{ record }">
          {{ record.cate_name }}
        </template>
        <!-- 排序 -->
        <template #sort="{ record }">
          {{ record.sort }}
        </template>
        <!-- 状态 -->
        <template #is_show="{ record }">
          <a-switch checked-children="显示" un-checked-children="隐藏" :checked="record.is_show == 1" @click="editStatus(record)" />
        </template>
        <!-- 操作 -->
        <template #operation="{ record }">
          <div class="editable-row-operations">
            <span> <a @click="seeFile(record)">查看附件</a>&nbsp; </span>
            <span> <a @click="updateFile(record)">上传附件</a>&nbsp; </span>
            <span> <a @click="() => editRowIndex(record)">编辑</a>&nbsp; </span>
            <span> <a @click="delRowIndex(record)">删除</a>&nbsp; </span>
          </div>
        </template>
      </ele-pro-table>
    </a-card>
  </div>
  <!-- 编辑弹窗 -->
  <a-modal v-model:visible="editCateDia" title="编辑分类" @cancel="editHandleCancel" width="700px">
    <template #footer>
      <a-button key="back" @click="editCateOk">确定</a-button>
      <a-button key="submit" type="primary" @click="editHandleCancel">取消</a-button>
    </template>
    <a-form :model="editForm" :label-col="labelCol" :wrapper-col="wrapperCol" :rules="editFormRules" ref="editFormRef">
      <a-form-item label="上级分类">
        <a-select v-model:value="editForm.pid" :options="cateListOption"> </a-select>
      </a-form-item>
      <a-form-item label="分类名称中文" name="cateName_zh">
        <a-input v-model:value="editForm.cateName_zh" placeholder="请输入分类名称" />
      </a-form-item>
      <a-form-item label="分类名称英文" name="cateName_en">
        <a-input v-model:value="editForm.cateName_en" placeholder="请输入分类名称" />
      </a-form-item>
      <a-form-item label="分类名称德语" name="cateName_de">
        <a-input v-model:value="editForm.cateName_de" placeholder="请输入分类名称" />
      </a-form-item>
      <a-form-item label="排序">
        <a-input style="width: 100px;" v-model:value="editForm.sort" type="number" :min="0" />
      </a-form-item>
      <a-form-item label="状态">
        <a-radio-group v-model:value="editForm.is_show">
          <a-radio :value="1">显示</a-radio>
          <a-radio :value="0">隐藏</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 添加分类弹窗 -->
  <a-modal v-model:visible="addCateDia" title="添加分类" width="700px" @cancel="handleCancel">
    <template #footer>
      <a-button key="back" @click="addCateOk">确定</a-button>
      <a-button key="submit" type="primary" @click="handleCancel">取消</a-button>
    </template>
    <a-form :model="addForm" :label-col="labelCol" :wrapper-col="wrapperCol" ref="addFormRef" :rules="addFormRules">
      <a-form-item label="上级分类">
        <a-select v-model:value="addForm.pid" :options="cateListOption"> </a-select>
      </a-form-item>
      <a-form-item label="分类名称中文" name="cateName_zh" ref="name">
        <a-input v-model:value="addForm.cateName_zh" placeholder="请输入分类名称" />
      </a-form-item>
      <a-form-item label="分类名称英文" name="cateName_en">
        <a-input v-model:value="addForm.cateName_en" placeholder="请输入分类名称" />
      </a-form-item>
      <a-form-item label="分类名称德语" name="cateName_de">
        <a-input v-model:value="addForm.cateName_de" placeholder="请输入分类名称" />
      </a-form-item>
      <a-form-item label="排序">
        <a-input style="width: 100px;" v-model:value="addForm.sort" type="number" :min="0" />
      </a-form-item>
      <a-form-item label="状态">
        <a-radio-group v-model:value="addForm.is_show">
          <a-radio :value="1">显示</a-radio>
          <a-radio :value="0">隐藏</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
  <!-- 添加附件弹窗 -->
  <a-modal v-model:visible="addFujianDia" title="上传附件" width="700px" @cancel="handleCancelFujian">
    <template #footer>
      <a-button key="back" @click="addFujianOk" type="primary">确定</a-button>
    </template>
    <a-form-item label="选择国家:">
      <a-select v-model:value="selectGuojia" :options="guojiaOption"> </a-select>
    </a-form-item>
    <a-form-item label="选择类型:">
      <a-select v-model:value="selectGuojiaLx" :options="guojiaOptionLx"> </a-select>
    </a-form-item>
    <a-form-item label="选择文件:">
      <a-upload name="file" list-type="picture-card picture" :show-upload-list="false" class="file-uploader" :custom-request="data => onFileUpload(data)">
        <img v-if="is_img" style="width:100px; height:100px;" :src="imgUrl" />
        <div v-else-if="is_img == false" class="ant-upload-text">非图片文件</div>
        <div v-else>
          请选择
        </div>
      </a-upload>
    </a-form-item>
  </a-modal>
  <!-- 查看附件的弹窗 -->
  <a-modal v-model:visible="seeFujianDia" title="查看附件" width="70%" @cancel="seeFujianClose">
    <template #footer>
      <a-button key="back" @click="seeFujianOk">确定</a-button>
      <a-button key="submit" type="primary" @click="seeFujianClose">取消</a-button>
    </template>
    <ele-pro-table ref="table" row-key="id" :datasource="seeFujianLists" :columns="fujianColumns" :scroll="{ x: 'max-content' }">
      <!-- ID -->
      <template #id="{ record }">
        {{ record.id }}
      </template>
      <!-- 分类明 -->
      <template #file_name="{ record }">
        {{ record.file_name }}
      </template>
      <!-- 排序 -->
      <template #type="{ record }">
        {{ record.type }}
      </template>
      <template #country="{ record }">
        {{ record.country }}
      </template>
      <template #chaOxia="{ record }">
        <span>
          <a @click="fujiandelRowIndexcOx(record)">{{ record.chaOxia }}</a
          >&nbsp;
        </span>
      </template>
      <!-- 操作 -->
      <template #operation="{ record }">
        <div class="editable-row-operations">
          <span> <a @click="fujiandelRowIndex(record)">删除</a>&nbsp; </span>
        </div>
      </template>
    </ele-pro-table>
  </a-modal>
</template>

<script>
import { createVNode } from 'vue'
import qs from 'qs'
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { mapGetters } from 'vuex'

export default {
  name: 'SystemUser',
  components: {
    PlusOutlined
  },
  computed: {
    ...mapGetters(['permission'])
  },
  data() {
    return {
      // 商品列表数据
      cateLists: [],
      columns: [
        {
          title: 'ID',
          dataIndex: 'id'
        },
        {
          title: '分类名称',
          dataIndex: 'cate_name'
        },
        {
          title: '排序',
          dataIndex: 'sort'
        },
        {
          title: '状态',
          dataIndex: 'is_show',
          align: 'center',
          slots: { customRender: 'is_show' }
        },
        {
          title: '编辑',
          slots: { customRender: 'operation' }
        }
      ],
      // 表格搜索条件
      where: {},
      // 表格选中数据
      selection: [],
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      // 分类名称
      searchName: '',
      // 新建分类的对话框
      addCateDia: false,
      // 添加分类数据
      addForm: {
        pid: 0,
        cateName_zh: '',
        cateName_en: '',
        cateName_de: '',
        sort: 100,
        is_show: 1
      },
      // 添加数据的验证
      addFormRules: {
        cateName_zh: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ],
        cateName_en: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ],
        cateName_de: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ]
      },
      // 编辑的弹窗控制
      editCateDia: false,

      // 商品分类的选择框
      options: [],
      // 商品分类状态的选择框
      statusOption: [
        { label: '全部', value: '' },
        { label: '显示', value: '1' },
        { label: '隐藏', value: '0' }
      ],
      // 表格的查询条件
      findOptions: {
        pid: null,
        is_show: null,
        cate_name: null
      },
      // 跳出添加分类弹窗获取的商品分类
      cateListOption: [],
      // 编辑的form表单数据
      editForm: {},
      // 编辑数据的验证
      editFormRules: {
        cateName_zh: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ],
        cateName_en: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ],
        cateName_de: [
          {
            required: true,
            message: '内容不能为空',
            trigger: 'blur'
          }
        ]
      },
      // 添加附件的弹窗控制
      addFujianDia: false,
      // 上传图片的id
      updateID: null,
      // 选择国家的数据
      guojiaOption: [
        {
          label: 'zh',
          value: 'zh'
        },
        {
          label: 'en',
          value: 'en'
        },
        {
          label: 'de',
          value: 'de'
        }
      ],
      guojiaOptionLx: [
        {
          label: '关键字',
          value: '关键字'
        },
        {
          label: '优化',
          value: '优化'
        },
        {
          label: '其他',
          value: '其他'
        }
      ],
      // 选择的国家
      selectGuojia: 'zh',
      selectGuojiaLx: '优化',
      // 上传图片的地址
      imgUrl: '',
      // 判断是否是图片
      is_img: null,
      // 查看附件
      seeFujianDia: false,
      // 查看列表列表数据
      seeFujianLists: [],
      // 查看附加列表
      fujianColumns: [
        {
          title: 'ID',
          dataIndex: 'id'
        },
        {
          title: '附件名称',
          dataIndex: 'file_name'
        },
        {
          title: '附件类型',
          dataIndex: 'type'
        },
        {
          title: '附件语言',
          dataIndex: 'country'
        },
        {
          title: '查看/下载',
          dataIndex: 'chaOxia',
          slots: { customRender: 'chaOxia' }
        },
        {
          title: '编辑',
          slots: { customRender: 'operation' }
        }
      ],
      // 查询附件的参数
      fujainChaxunId: null
    }
  },
  created() {
    this.getCateLists()
    this.getLanmuLists()
  },
  methods: {
    /* 获取商品分类列表 */
    async getCateLists() {
      const { data: res } = await this.$http.get('/product/category?lang=zh', { params: this.findOptions })
      console.log(res)
      this.cateLists = res.data.list
      console.log(this.findOptions)
      console.log(this.cateLists)
    },
    /* 修改用户状态 */
    async editStatus(row) {
      let flog = null
      if (row.is_show == 0) {
        flog = 1
      } else {
        flog = 0
      }
      const res = await this.$http.post('/product/category/display', qs.stringify({ id: row.id, is_show: flog }))
      console.log(res)
      if (res.status == 200) {
        this.$message.success('切换成功！')
        this.getCateLists()
      }
    },
    // 获取select数据
    async getLanmuLists() {
      const res = await this.$http.get('/product/category?lang=zh')
      console.log(res.data.data.list)
      let arr = res.data.data.list
      let newArr = [{ label: '全部', value: '' }]
      arr.forEach(element => {
        let folg = 'children' in element

        if (!folg) {
          newArr.push({
            label: '|----' + element.cate_name,
            value: element.id
            // disabled: false
          })
        } else {
          element.children.forEach(aitem => {
            if ('children' in aitem) {
              newArr.push({
                label: '|----' + element.cate_name,
                value: element.id
                // disabled: true
              })
              newArr.push({
                label: '|----|----' + aitem.cate_name,
                value: aitem.id
                // disabled: true
              })
              aitem.children.forEach(item2 => {
                newArr.push({
                  label: '|----|----|----' + item2.cate_name,
                  value: item2.id
                  // disabled: false
                })
              })
            } else {
              console.log('children' in element.children)
              newArr.push({
                label: '|----' + element.cate_name,
                value: element.id
                // disabled: true
              })
              newArr.push({
                label: '|----|----' + aitem.cate_name,
                value: aitem.id
                // disabled: false
              })
            }
          })
        }
      })
      this.options = newArr
    },
    // 封装获取选择框的数据
    async getSelectOption() {
      const { data: res } = await this.$http.get('/product/category?lang=zh')
      let arr = []
      res.data.list.forEach(element => {
        arr.push({ label: element.cate_name, value: element.id })
      })
      arr.unshift({ label: '顶级菜单', value: 0 })
      this.cateListOption = arr
      console.log(this.cateListOption)
    },
    // 打开新建弹窗
    async openAddCate() {
      this.addCateDia = true
      this.getSelectOption()
    },
    // 确认添加分类
    addCateOk() {
      // console.log(this.$refs.addFormRef.validate);
      this.$refs.addFormRef
        .validate()
        .then(async () => {
          let sends = {
            pid: this.addForm.pid,
            'cate_name[zh]': this.addForm.cateName_zh,
            'cate_name[en]': this.addForm.cateName_en,
            'cate_name[de]': this.addForm.cateName_de,
            sort: this.addForm.sort,
            is_show: this.addForm.is_show
          }
          const res = await this.$http.post('/product/category/create', qs.stringify(sends))
          console.log(res)
          this.$message.success('添加分类成功')
          this.addCateDia = false
          this.addForm = {
            pid: 0,
            cateName_zh: '',
            cateName_en: '',
            cateName_de: '',
            sort: 100,
            is_show: 1
          }
          this.getCateLists()
        })
        .catch(error => {
          console.log('error', error)
          this.$message.info('添加失败！')
        })
    },
    // 取消添加分类
    handleCancel() {
      this.$refs.addFormRef.clearValidate()
      this.addForm = {
        pid: 0,
        cateName_zh: '',
        cateName_en: '',
        cateName_de: '',
        sort: 100,
        is_show: 1
      }
      this.addCateDia = false
    },
    // 编辑按钮
    async editRowIndex(row) {
      this.getSelectOption()
      const { data: res } = await this.$http.get('/product/category/show?id=' + row.id)
      let newObj = {
        pid: parseInt(res.data.pid),
        cateName_zh: res.data.cate_name.zh,
        cateName_en: res.data.cate_name.en,
        cateName_de: res.data.cate_name.de,
        sort: res.data.sort,
        is_show: res.data.is_show,
        id: row.id
      }
      this.editForm = newObj
      console.log(this.editForm)
      console.log(this.cateListOption)
      this.editCateDia = true
    },
    // 删除
    delRowIndex(row) {
      this.$confirm({
        title: '确定删除？',
        content: '删除后将无法恢复',
        okText: '确定',
        cancelText: '取消',
        icon: createVNode(ExclamationCircleOutlined),
        onOk: async () => {
          const res = await this.$http.delete('/product/category/' + row.id)
          console.log(res)
          if (res.data.code == 0) {
            this.$message.success('删除分类成功')
            this.getCateLists()
          }
        },
        onCancel: () => {
          this.$message.info('取消操作')
        }
      })
    },
    // 编辑弹窗关闭的回调
    editHandleCancel() {
      this.editCateDia = false
    },
    // 编辑弹窗确定的回调
    editCateOk() {
      this.$refs.editFormRef
        .validate()
        .then(async () => {
          let sends = {
            id: this.editForm.id,
            pid: this.editForm.pid,
            cate_name: {
              zh: this.editForm.cateName_zh,
              en: this.editForm.cateName_en,
              de: this.editForm.cateName_de
            },
            sort: this.editForm.sort,
            is_show: this.editForm.is_show
          }
          const res = await this.$http.post('/product/category/update', qs.stringify(sends))
          if (res.data.code != 0) return this.$message.warning('编辑失败')
          this.$message.success('编辑成功')
          this.getCateLists()
          this.editCateDia = false
        })
        .catch(error => {
          console.log(error)
          this.$message.warning('编辑失败')
        })
    },
    // 上传附件
    updateFile(row) {
      console.log(row.id)
      this.updateID = row.id
      this.addFujianDia = true
    },
    // 添加附件的关闭
    handleCancelFujian() {
      this.addFujianDia = false
    },
    // 添加附件的确定回调
    addFujianOk() {
      this.addFujianDia = false
      this.selectGuojia = 'zh'
      this.selectGuojiaLx = '优化'
      this.is_img = null
    },
    // 上传附件的接口调用
    async onFileUpload(file) {
      // this.loading[type] = true;
      console.log(file)
      const formData = new FormData()
      formData.append('category_id', this.updateID)
      formData.append('file', file.file)
      formData.append('country', this.selectGuojia)
      formData.append('class_name', this.selectGuojiaLx)
      const res = await this.$http.post('/product/category/accessory', formData)
      console.log(res)
      if (res.data.code != 0) return this.$message.info('文件或者图片上传失败！')

      if (res.data.data.type == 'gif' || res.data.data.type == 'jpg' || res.data.data.type == 'png') {
        this.is_img = true
      } else {
        this.is_img = false
      }
      console.log(this.is_img)
      // this.imgUrl = "https://3z7091u275.zicp.fun/product/" + res.data.data.path;
      this.imgUrl = process.env.VUE_APP_API_BASE_URL + '/uploads/' + res.data.data.path
      this.$message.success('文件或者图片上传成功！')
      // formData = new FormData()
    },
    // 查看附件的打开按钮
    async seeFile(row) {
      this.fujainChaxunId = row.id
      const res = await this.$http.get('/product/category/accessory?category_id=' + row.id)
      console.log(res.data.data)
      res.data.data.forEach(item => {
        if (item.type == 'gif' || item.type == 'jpg' || item.type == 'png') {
          item.chaOxia = '查看'
        } else {
          item.chaOxia = '下载'
        }
      })
      this.seeFujianLists = res.data.data
      this.seeFujianDia = true
    },
    // 关闭查看附件
    seeFujianClose() {
      this.seeFujianDia = false
    },
    // 查看附件确定回调
    seeFujianOk() {
      this.seeFujianDia = false
    },
    // 附件删除
    async fujiandelRowIndex(row) {
      console.log(row.id)
      const res = await this.$http.delete('/product/category/accessory/' + row.id)
      console.log(res)
      const ress = await this.$http.get('/product/category/accessory?category_id=' + this.fujainChaxunId)
      //  if(res.data.code == 0) return this.$message.success("删除成功")
      this.seeFujianLists = ress.data.data
    },
    // 查看或者下载附件
    fujiandelRowIndexcOx(row) {
      if (row.chaOxia == '查看') {
        let href = process.env.VUE_APP_API_BASE_URL + '/uploads/' + row.path
        window.open(href, '_blank')
      } else {
        let a = document.createElement('a')
        a.href = process.env.VUE_APP_API_BASE_URL + '/uploads/' + row.path
        a.download = row.file_name
        a.style.display = 'none'
        document.body.appendChild(a)
        a.click()
        a.remove()
      }
    }
  }
}
</script>

<style scoped lang="less">
.tital_war {
  width: 100%;
  height: 50px;
  background: #fff;
  margin-bottom: 10px;
  display: flex;
  align-items: center;
  h1 {
    margin: 0;
    padding: 0;
    margin-left: 10px;
    font-size: 22px;
    font-weight: 500;
  }
}
</style>
